
const checkUpdate = {
  // 版本号比较函数
  compareVersion(v1, v2) {
    const v1Parts = v1.split('.');
    const v2Parts = v2.split('.');
    
    for (let i = 0; i < v1Parts.length; i++) {
      const v1Num = parseInt(v1Parts[i]);
      const v2Num = parseInt(v2Parts[i] || 0);
      if (v1Num > v2Num) return 1;
      if (v1Num < v2Num) return -1;
    }
    return v1Parts.length >= v2Parts.length ? 0 : -1;
  },

  // 检查更新
  check() {
    return new Promise((resolve, reject) => {
      // 获取当前应用版本号
      plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
        const currentVersion = widgetInfo.version;
        console.log(currentVersion)
        // 请求服务器版本信息
        uni.request({
          url: 'http://43.138.215.11:3384/get_version',
		  method:'POST',
		  data:{},
		  // sslVerify:false,
          success: (res) => {
            const serverData = res.data;
            // 在前端进行版本比较
			console.log(serverData)
            const hasUpdate = this.compareVersion(serverData.version, currentVersion) > 0;
            if (hasUpdate) {
              resolve({
                update: true,
                version: serverData.version,
                url: serverData.downloadUrl,
                changelog: serverData.changelog
              });
            } else {
              resolve({
                update: false
              });
            }
          },
          fail: (err) => {
			
            reject(err);
          }
        });
      });
    });
  },

  // 下载更新包
  downloadAPK(url) {
    return new Promise((resolve, reject) => {
      const downloadTask = uni.downloadFile({
        url: url,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.tempFilePath);
          } else {
            reject(new Error('下载失败'));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });

      // 监听下载进度
      downloadTask.onProgressUpdate((res) => {
        uni.$emit('updateProgress', {
          progress: res.progress
        });
      });
    });
  },

  // 安装APK
  installAPK(filePath) {
    return new Promise((resolve, reject) => {
      plus.runtime.install(filePath, {
        force: false
      }, () => {
        resolve();
      }, (err) => {
        reject(err);
      });
    });
  }
};

export default checkUpdate;